<!DOCTYPE html>
<html>
	<head>
		<title>WordPress Playground</title>
		<style>
			* {
				box-sizing: border-box;
			}

			html,
			body,
			#wp {
				height: 100%;
				width: 100%;
				margin: 0;
				padding: 0;
				border: 0;
			}

			html,
			body {
				overflow: hidden;
			}

			body.has-error {
				padding: 15px;
				background: #f1f1f1;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				font-size: 20px;
				font-family: Arial, Helvetica, sans-serif;
				line-height: 1.4;
			}
			body.has-error .error-message {
				padding: 20px;
				max-width: 800px;
			}
			body.has-error button {
				margin-top: 15px;
				margin-bottom: 15px;
				font-size: 20px;
				padding: 5px 10px;
				cursor: pointer;
			}

			@media (prefers-color-scheme: dark) {
				body.is-loading,
				body.has-error {
					background: #1e1e1e;
					color: #fff;
				}
			}
		</style>
		<!-- TODO: Support inserting other origin-trial codes on build, so self-hosted Playground can opt into the trials. -->
		<!--
		Enable the JSPI origin trial.
		Refresh periodically at https://developer.chrome.com/origintrials/#/trials/active
		The current registration ands on Feb 19th 2025.
		-->
		<!-- https://playground.wordpress.net -->
		<meta
			http-equiv="origin-trial"
			content="Ao+kSl7oykDGDxe74ym6/PXY71Xh0V4F0JoU9Sxrge9U8PfuTx7kZsNi2c24angA3UUtyl1DtMj/KkNfTWz7+wgAAABxeyJvcmlnaW4iOiJodHRwczovL3BsYXlncm91bmQud29yZHByZXNzLm5ldDo0NDMiLCJmZWF0dXJlIjoiV2ViQXNzZW1ibHlKU1Byb21pc2VJbnRlZ3JhdGlvbiIsImV4cGlyeSI6MTczOTkyMzE5OX0="
		/>
		<!-- https://wasm.wordpress.net -->
		<meta
			http-equiv="origin-trial"
			content="AqzvSQwvBB08ydkKZEZrihGqL0Y/IGa6lzA90n6uKssfAtCWc22FoMr/EbwWQY8swkPNnxH+ubiWa8KduRp0qQ0AAABreyJvcmlnaW4iOiJodHRwczovL3dhc20ud29yZHByZXNzLm5ldDo0NDMiLCJmZWF0dXJlIjoiV2ViQXNzZW1ibHlKU1Byb21pc2VJbnRlZ3JhdGlvbiIsImV4cGlyeSI6MTczOTkyMzE5OX0="
		/>
		<!-- http://127.0.0.1:5400 -->
		<meta
			http-equiv="origin-trial"
			content="Ahmn8GVmGU9NRHarIHfjO3xPt/PI3V/XfXD0fLMco+6cFTYUcF7v63+y+PZDtJHge2HXNWuoZajUMHYydAVuTw8AAABieyJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjU0MDAiLCJmZWF0dXJlIjoiV2ViQXNzZW1ibHlKU1Byb21pc2VJbnRlZ3JhdGlvbiIsImV4cGlyeSI6MTczOTkyMzE5OX0="
		/>
	</head>
	<body class="is-loading">
		<iframe
			id="wp"
			title="The WordPress site"
			sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-downloads allow-modals"
		></iframe>
		<script type="module">
			if (window.top != window.self) {
				document.body.classList.add('is-embedded');
			}
			import { bootPlaygroundRemote } from './src/index';
			try {
				window.playground = await bootPlaygroundRemote();
			} catch (e) {
				console.error(e);
				document.body.className = 'has-error';
				document.body.innerHTML = '';

				if (e?.name === 'NotSupportedError') {
					document.body.append(await renderStorageErrorUI());
				} else {
					document.body.append(renderGenericErrorUI(e));
				}
			} finally {
				document.body.classList.remove('is-loading');
			}

			function renderGenericErrorUI(error) {
				const fragment = document.createDocumentFragment();

				const div = document.createElement('div');
				div.className = 'error-message';
				const userFriendlyMessage =
					error.userFriendlyMessage ||
					'See the developer tools for error details.';
				div.innerHTML =
					'Ooops! WordPress Playground had a hiccup! <br/><br/> ' +
					userFriendlyMessage;
				fragment.append(div);

				const button = document.createElement('button');
				button.innerText = 'Try again';
				button.onclick = () => {
					window.location.reload();
				};
				fragment.append(button);

				const reportIssues = document.createElement('p');
				reportIssues.innerHTML = `
					If the problem persists, please
					<a href="https://github.com/WordPress/playground-tools/issues/new"
						target="_blank"
						>report an issue on GitHub</a>.
				`;
				fragment.append(reportIssues);

				return fragment;
			}

			async function renderStorageErrorUI() {
				const fragment = document.createDocumentFragment();

				/**
				 * Chrome does not allow Service Workers to be registered from cross-origin iframes
				 * when third-party cookies are disabled unless `requestStorageAccess()` is called
				 * and the user grants storage access.
				 *
				 * Let's assess the situation and provide a helpful message.
				 */
				let hasStorageAccess = false;
				try {
					const { state } = await navigator.permissions.query({
						name: 'storage-access',
					});
					hasStorageAccess = state === 'granted';
				} catch (e) {
					// noop
				}

				if (hasStorageAccess || !('requestStorageAccess' in document)) {
					const div = document.createElement('div');

					// The user has granted storage access, but the error still persists.
					// Let's explain why.
					div.innerText =
						'It looks like you have disabled third-party cookies in your browser. This ' +
						'also disables the Service Worker API used by WordPress Playground. Please re-enable ' +
						'third-party cookies and try again.';
					fragment.append(div);

					const button = document.createElement('button');
					button.innerText = 'Try again';
					button.onclick = () => {
						window.location.reload();
					};
					fragment.append(button);
				} else {
					const div = document.createElement('div');

					// The user has not granted storage access.
					// There's a chance we can fix this by asking for storage access.
					div.innerText =
						'WordPress Playground needs to use storage in your browser.';
					fragment.append(div);

					const button = document.createElement('button');
					button.innerText = 'Allow storage access';
					fragment.append(button);

					button.onclick = async () => {
						try {
							await document.requestStorageAccess();
							window.location.reload();
						} catch (e) {
							// Either the user denied storage access OR chrome is not allowing
							// storage access to be requested from an iframe for some reason.

							// The two errors are indistinguishable and just say "requestStorageAccess not allowed"
							// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/dom/document.cc;drc=daf56cfa413f10dee6aa15b0b1e4572fcf5578df;l=462
							// It's confusing! But we can at least tell the user what to do.
							div.innerHTML = `
								<p>
									Oops! Playground failed to start. Here's what to do:
								</p>

								<h3>Did you disable third-party cookies?</h3>
								<p>
									It also disables the required Service Worker API. Please re-enable
									third-party cookies and try again.
								</p>

								<h3>Did you refuse to grant Playground storage access?</h3>
								<p>
									Click the button below and grant storage access. Note the button may
									not work if you have disabled third-party cookies in your browser.
								</p>
								<p>
									If neither method helped, please
									<a href="https://github.com/WordPress/playground-tools/issues/new"
										target="_blank">
										report an issue on GitHub
									</a>.
								</p>
								`;
						}
					};
				}

				return fragment;
			}
		</script>
	</body>
</html>
